const socket = require('socket.io')
const db = require('../mysql/index')
const expressJWT = require('express-jwt')
const setting = require('../setting')
const jwt = require('jsonwebtoken');
function send_err(socket, message) {
    socket.emit('send-err', message)
}
const emojiEncode = (e) => {
    let n = /[\ud800-\udbff][\udc00-\udfff]/g;
    // let n
    // 检测utf16字符正则
    return e = e.replace(n, function (e) {
        let n, r;
        return 2 === e.length ? (n = e.charCodeAt(0), r = e.charCodeAt(1),
            "&#" + (1024 * (n - 55296) + 65536 + r - 56320) + ";") : e
    })
}


const emojiDecode = (e) => {
    let n = /&#.*?;/g; //获取数据库种16进制的数据
    //然后进行解码操作
    return e.replace(n, function (e) {
        let n, r, t;
        return 9 == e.length ? (t = parseInt(e.match(/[0-9]+/g)), n = Math.floor((t - 65536) / 1024) +
            55296, r = (t - 65536) % 1024 + 56320, unescape("%u" + n.toString(16) + "%u" + r
                .toString(16))) : e
    })
}
exports.getSocket = (server) => {
    const io = socket(server, {
        cors: {
            origin: '*'
        }
    })
    const userList = []
    io.on('connection', (socket) => {
        const token = socket.handshake.auth.token;
        let id = jwt.verify(token, setting.mySecret).id
        const userInfo = userList.find(user => user.userId === id)
        if (userInfo) {
            userInfo.id = socket.id
        } else {
            userList.push({
                id: socket.id,
                userId: id
            })
        }
        socket.on('clear-chat-num', (from) => {
            db.query('UPDATE bilibili_chat SET is_look=1 where `to`=? and `from` = ?', [id, from], (err, res) => {
                db.query('select `is_look` from bilibili_chat where `to` =?', [id], (err, my_res) => {
                    let newArr = my_res.filter((item) => !item.is_look)
                    socket.emit('chat-num', newArr.length)
                })
            })
        })
        socket.on('send', ({ to, message }) => {
            const user = userList.find(user => user.userId == to)
            reciceId = io.sockets.sockets.get(user ? user.id : null)
            socket.emit('send-success', message)
            reciceId && reciceId.timeout(300).emit('receive', message, async (err) => {
                message = emojiEncode(message)
                if (err) {
                    await new Promise(resolve => {
                        db.query('insert into bilibili_chat (`from`, `to`, `message`, `time`, `is_look`) values(?, ?, ?, ?,?)', [id, to, message, Date.now(), 0], () => {
                            resolve()
                        })
                    })
                } else {
                    await new Promise(resolve => {
                        db.query('insert into bilibili_chat (`from`, `to`, `message`, `time`, `is_look`) values(?, ?, ?, ?,?)', [id, to, message, Date.now(), 1], () => {
                            resolve()
                        })
                    })
                }
                reciceId.emit('updateChatList')
                db.query('select `is_look` from bilibili_chat where `to` =?', [to], (err, my_res) => {
                    let newArr = my_res.filter((item) => !item.is_look)
                    if (reciceId) reciceId.emit('chat-num', newArr.length)
                })
            })
            if (!reciceId) {
                db.query('insert into bilibili_chat (`from`, `to`, `message`, `time`, `is_look`) values(?, ?, ?, ?,?)', [id, to, message, Date.now(), 0])
            }
        })
    })
}